package com.sentiment.db;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.bson.Document;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.sentiment.config.Config;
import com.sentiment.obj.Text;

public class TextDB {
	private MongoClient mongoClient;
	private MongoDatabase mongodb;
	private MongoCollection<Document> mongoCollection;
	private Logger logger = Config.getLogger(this.getClass());

	public TextDB() {

		mongoClient = new MongoClient();

		mongodb = mongoClient.getDatabase("detection");

		mongoCollection = mongodb.getCollection("txCollection");
	}

	public void DBClose() {
		mongoClient.close();
	}

	/**
	 * @param data
	 *            待存入数据库的数据结构
	 */
	public void insertData(Text data) {
		//
		Document content = data.getContent();
		logger.info("-----存入数据库中的content文本------");
		logger.info(content.toJson());

		// 创建一个document并插入
		Document doc = new Document().append("title", data.getTitle()).append("content", content)
				.append("id", data.getId()).append("writer", data.getWriter()).append("publishTime", data.getPublishTime());

		mongoCollection.insertOne(doc);
	}

	public Text findDataByKeyAndVal(String key, Object val) {
		Document doc = mongoCollection.find(Filters.eq(key, val)).first();
		if(doc == null){
			return null;
		}
		Text tx = new Text(doc);

		return tx;
	}

	public List<Text> findAllDataByKeyAndVal(String key, Object val) {
		final List<Text> txArr = new ArrayList<Text>();
		mongoCollection.find(Filters.eq(key, val)).forEach(new Block<Document>() {
			@Override
			public void apply(final Document doc) {
				// TODO Auto-generated method stub
				Text tx = new Text(doc);
				
				txArr.add(tx);
			}
		});
		return txArr;
	}

	public void cleanAll() {
		// 清理掉collection中原有的数据
		mongoCollection.drop();
	}

}
